package com.wbdgj.ui.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.google.gson.internal.LinkedTreeMap;
import com.igexin.sdk.PushManager;
import com.wbdgj.R;
import com.wbdgj.adapter.FootprintBranchAdapter;
import com.wbdgj.adapter.WbAdapter;
import com.wbdgj.adapter.WbNewAdapter;
import com.wbdgj.adapter.ZdAdapter;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.base.BaseFragment;
import com.wbdgj.base.BaseWhiteFragment;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.HttpPointAdapter;
import com.wbdgj.http.OnNoResponseListener;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.model.ResultPointModel;
import com.wbdgj.ui.WebViewActivity;
import com.wbdgj.ui.booking.BookingActivity;
import com.wbdgj.ui.branch.BranchDetailActivity;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.ui.mine.CjMyActivity;
import com.wbdgj.ui.mine.EwmActivity;
import com.wbdgj.ui.mine.MyEwmActivity;
import com.wbdgj.ui.mine.PointActivity;
import com.wbdgj.ui.mine.PointNewActivity;
import com.wbdgj.ui.mine.VerifiedActivity;
import com.wbdgj.ui.mine.YhjActivity;
import com.wbdgj.ui.store.StoreCofeActivity;
import com.wbdgj.ui.store.StoreHotelActivity;
import com.wbdgj.ui.word_compaign.WordCompaignActivity;
import com.wbdgj.utils.CommonUtils;
import com.wbdgj.utils.EasyAbsListView;
import com.wbdgj.utils.EasyLineView;
import com.wbdgj.utils.HorizontalListView;
import com.wbdgj.utils.ListViewForScrollView;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;
import com.wbdgj.utils.dialog.ConfirmDialog;
import com.wbdgj.utils.dialog.LoadingDialog;
import com.wbdgj.utils.refresh.PullListView;
import com.wbdgj.utils.scrollablelayout.ScrollableLayout;

import com.zaaach.citypicker.CityPickerActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit2.Call;

/**
 * Created by Administrator on 2018/5/2.
 */

public class HomeFragment extends BaseWhiteFragment implements PtrHandler{

    private Context context;
    @BindView(R.id.pfl_root)
    PtrClassicFrameLayout pfl_root;

    @BindView(R.id.scrollView)
    ScrollView scrollView;

    private static final int REQUEST_CODE_PICK_CITY = 233;
    @BindView(R.id.tv_leftTitle)
    TextView tv_leftTitle;

    @BindView(R.id.demo_listview)
    ListViewForScrollView myPullListView;
    @BindView(R.id.zdList)
    HorizontalListView zdList;

    @BindView(R.id.yhq_gg)
    ImageView yhq_gg;

    @BindView(R.id.pointXx)
    ImageView pointXx;

    private FootprintBranchAdapter wbAdapter;
    private ZdAdapter zdAdapter;

    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
//    private ArrayList<Integer> localImages = new ArrayList<Integer>();
    private ArrayList<String> localImages = new ArrayList<String>();

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;


    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private String COORDSX, COORDSY, PROVINCE, CITY, DISTRICT;

    //全局的jsonObject
    private JSONObject jsonObject;//把全国的省市区的信息以json的格式保存，解析完成后赋值为null
    private String[] allProv;//所有的省

    //省市区的集合
    private Map<String, String[]> cityMap = new HashMap<String, String[]>();//key:省p---value:市n  value是一个集合
    private Map<String, String[]> areaMap = new HashMap<String, String[]>();//key:市n---value:区s    区也是一个集合

    private Boolean isSm = false;

    @Override
    protected int getLayout() {
        return R.layout.ui_home;
    }

    LoadingDialog dialog;

    private String wsyNum ,ysyNum , ygqNum;

    private void appCouponlist() {

        Call<ResultObjectModel> call01 = HttpAdapter.getSerives().getTotals(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call01.enqueue(new OnNoResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    wsyNum = decimalFormat.format(linkedTreeMap.get("UNUSED"));
                    ysyNum = decimalFormat.format(linkedTreeMap.get("USED"));
                    ygqNum = decimalFormat.format(linkedTreeMap.get("DUE"));
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });

    }

    @Override
    protected void onInit() {
        context = getActivity();
        dialog = new LoadingDialog(context);
        dialog.setText("正在定位中...");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(context,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 10);
            }
        }
        scrollView.scrollTo(0,0);
        pfl_root.setEnabledNextPtrAtOnce(true);
        pfl_root.setLastUpdateTimeRelateObject(this);
        pfl_root.setPtrHandler(this);
        pfl_root.setKeepHeaderWhenRefresh(true);
        pfl_root.disableWhenHorizontalMove(true);
        initLocation();
        indexAdvertising();
        slideShow();
        appCouponlist();
        upbranchlist();
        getMbUserInfo();
//        inittable();
        myPullListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                if (!wbAdapter.hasNoData){
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.HOTEL_ID, decimalFormat.format(wbAdapter.getItem(i).get("branch_id")));
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.HOTEL_NAME, wbAdapter.getItem(i).get("branch_name")+"");
                    if(wbAdapter.getItem(i).containsKey("branch_attributes")){
                        if(decimalFormat.format(wbAdapter.getItem(i).get("branch_attributes")).equals("0")){
                            startActivity(new Intent(context, StoreCofeActivity.class));
                        }else if(decimalFormat.format(wbAdapter.getItem(i).get("branch_attributes")).equals("1")){
                            startActivity(new Intent(context, BookingActivity.class));
                        }else{
                            startActivity(new Intent(context, StoreHotelActivity.class));
                        }
                    }else{
                        startActivity(new Intent(context, StoreCofeActivity.class));
                    }
                }
            }
        });
        zdList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!zdAdapter.hasNoData){
                    startActivity(new Intent(context, ZdDetailActivity.class).putExtra("id", zdAdapter.getItem(i).get("USER_ID")+""));
                }
            }
        });

        convenientBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (imgListLb.size()>0){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    if(decimalFormat.format(imgListLb.get(position).get("VISIT_TYPE")).equals("1")){
                        startActivity(new Intent(context, WordCompaignActivity.class).putExtra("id", decimalFormat.format(imgListLb.get(position).get("ACTVITY_ID"))));

                    }else if(decimalFormat.format(imgListLb.get(position).get("VISIT_TYPE")).equals("2")){
                        startActivity(new Intent(context, WebViewActivity.class).putExtra("url", imgListLb.get(position).get("URL")+"").putExtra("TITLE", imgListLb.get(position).get("TITLE")+"")
                                .putExtra("PATH", HttpAdapter.HEAD_URL+imgListLb.get(position).get("PATH")+""));
                    }
                }

            }
        });
    }

    private void upbranchlist() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().upbranchlist(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    List<LinkedTreeMap> linkedTreeMaps  = (List<LinkedTreeMap>) linkedTreeMap.get("data");
                    wbAdapter = new FootprintBranchAdapter(context, linkedTreeMaps);
                    myPullListView.setAdapter(wbAdapter);
                }
            }
        });
    }

    //为了方便改写，来实现复杂布局的切换
    private class LocalImageHolderView implements Holder<String> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，不一定是Image，任何控件都可以进行翻页
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            Glide.with(context).load(data).placeholder(R.mipmap.detail_wait).error(R.mipmap.detail_error).into(imageView);
        }
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    mLocationClient.stopLocation();
                    //可在其中解析amapLocation获取相应内容。
                    COORDSX =  "" + CommonUtils.gaoDeToBaidu(amapLocation.getLatitude(), amapLocation.getLongitude())[0];
                    COORDSY =  "" + CommonUtils.gaoDeToBaidu(amapLocation.getLatitude(), amapLocation.getLongitude())[1];
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.COORDSX, COORDSX);
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.COORDSY, COORDSY);
                    PROVINCE= amapLocation.getProvince().replaceAll("", "");
                    CITY = amapLocation.getCity().replaceAll("市", "");
                    DISTRICT = amapLocation.getDistrict().replaceAll("", "");
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    COORDSX =  "0" ;
                    COORDSY =  "0" ;
                }
                if (BaseApplication.getInstance().isFirstEnter()){
                    BaseApplication.getInstance().setNotFirstEnter();
                    tv_leftTitle.setText(CITY+"");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.CITY, CITY);
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.PROVINCE, PROVINCE);
                }else{
                    if ((BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CITY)+"").equals("null")){
                        tv_leftTitle.setText("定位失败");
                    }else{
                        tv_leftTitle.setText(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CITY));
                        if(!BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CITY).contains(CITY)){
                            final ConfirmDialog confirmDialog = new ConfirmDialog(context, 0, "定位到您在"+CITY+"\n是否切换至该城市进行搜索？", "切换", "取消", 1);
                            confirmDialog.show();
                            confirmDialog.setCanceledOnTouchOutside(false);
                            confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                                @Override
                                public void doConfirm() {
                                    confirmDialog.dismiss();
                                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.CITY, CITY);
                                    getLatlon(CITY);
                                    tv_leftTitle.setText(CITY);
//                                    queryAll("", BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CITY), "", "", "2");
                                }
                                @Override
                                public void doCancel() {
                                    confirmDialog.dismiss();
                                }
                            });
                        }

                    }
                }
                dialog.dismiss();
//                queryAll("", BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CITY), "", "", "2");
            }
        }
    };

    private void getMbUserInfo() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().getMbUserInfo(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnNoResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    if(linkedTreeMap.containsKey("NAME")){
                        if ((linkedTreeMap.get("NAME")+"").equals("null")){
                            isSm = true;
                        }else if((linkedTreeMap.get("NAME")+"").equals("")){
                            isSm = true;
                        }else{
                            isSm = false;
                            AddRemote(linkedTreeMap.get("ID_CARD")+"");
                        }
                    }else{
                        isSm = true;
                    }
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });
    }

    private void AddRemote(String ID_CARD) {
        Call<ResultPointModel> call = HttpPointAdapter.getSerives().AddRemote(ID_CARD);
        call.enqueue(new OnNoResponseListener<ResultPointModel>(context) {
            @Override
            protected void onSuccess(ResultPointModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getCode() ==200){
                    List<LinkedTreeMap> linkedTreeMapList = (List<LinkedTreeMap>) userModelBaseResultModel.getData();
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    if (linkedTreeMapList.size() != 0){
                        if(!linkedTreeMapList.toString().contains("null")){
                            BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.HOTEL_ID, decimalFormat.format(linkedTreeMapList.get(0).get("branch_id")));
                            BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.HOTEL_NAME, linkedTreeMapList.get(0).get("branch_name")+"");
                            if(linkedTreeMapList.get(0).containsKey("branch_attributes")){
                                if(decimalFormat.format(linkedTreeMapList.get(0).get("branch_attributes")).equals("0")){
                                    startActivity(new Intent(context, StoreCofeActivity.class));
                                }else if(decimalFormat.format(linkedTreeMapList.get(0).get("branch_attributes")).equals("1")){
                                    startActivity(new Intent(context, BookingActivity.class));
                                }else{
                                    startActivity(new Intent(context, StoreHotelActivity.class));
                                }
                            }else{
                                startActivity(new Intent(context, StoreCofeActivity.class));
                            }
                        }

                    }
                }
            }
        });
    }

    private void appmbmsgcnt() {
        Call<ResultObjectModel> call01 = HttpAdapter.getSerives().appmbmsgcnt(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call01.enqueue(new OnNoResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    if (decimalFormat.format(linkedTreeMap.get("CNT")).equals("0")){
                        pointXx.setVisibility(View.GONE);
                    }else{
                        pointXx.setVisibility(View.VISIBLE);
                    }
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });
    }

    private void initLocation() {
        dialog.show();
        //初始化定位
        mLocationClient = new AMapLocationClient(context);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @OnClick({R.id.tv_rightImg, R.id.home_xx_sys, R.id.home_xx_ss, R.id.yhq_gg, R.id.moreZD, R.id.tv_searchLay, R.id.tv_leftTitle, R.id.sys, R.id.cwf, R.id.jf, R.id.fkm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_rightImg:
                launch(NewsAllActivity.class);
                break;
            case R.id.home_xx_ss:
                startActivity(new Intent(context, SearchActivity.class));
                break;
            case R.id.home_xx_sys:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(context,
                            Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 10);
                    } else {
                        launch(ZXingActivity.class);
                    }
                } else {
                    launch(ZXingActivity.class);
                }
                break;
            case R.id.yhq_gg:
                if (imgListGg.size()==0){
                    ToastUtils.toastShort("暂时没有链接哦");
                }else{
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    if (decimalFormat.format(imgListGg.get(0).get("VISIT_TYPE")).equals("2")){
                        startActivity(new Intent(context, WebViewActivity.class).putExtra("url", imgListGg.get(0).get("URL")+"").putExtra("TITLE", imgListGg.get(0).get("TITLE")+"")
                                .putExtra("PATH", HttpAdapter.HEAD_URL+imgListGg.get(0).get("PATH")+""));
                    }else if(decimalFormat.format(imgListGg.get(0).get("VISIT_TYPE")).equals("1")){
                        startActivity(new Intent(context, WordCompaignActivity.class).putExtra("id", decimalFormat.format(imgListGg.get(0).get("ACTVITY_ID"))));
                    }

                }
                break;
            case R.id.moreZD:
                launch(MoreZdActivity.class);
                break;
            case R.id.tv_searchLay:
                startActivity(new Intent(context, SearchActivity.class));
                break;
            case R.id.tv_leftTitle:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(context,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 10);
                    } else {
                        startActivityForResult(new Intent(context, LoactionActivity.class),
                                REQUEST_CODE_PICK_CITY);
                    }

                } else {
                    startActivityForResult(new Intent(context, LoactionActivity.class),
                            REQUEST_CODE_PICK_CITY);
                }
                break;
            case R.id.sys:
                if (isSm){
                    startActivityForResult(new Intent(context, VerifiedActivity.class), 1);
                }else{
                    launch(MyEwmActivity.class);
                }
                break;
            case R.id.cwf:
                if (isSm){
                    startActivityForResult(new Intent(context, VerifiedActivity.class), 1);
                }else{
                    launch(CjMyActivity.class);
                }
                break;
            case R.id.jf:
                if (isSm){
                    startActivityForResult(new Intent(context, VerifiedActivity.class), 1);
                }else{
                    startActivity(new Intent(context, YhjActivity.class).putExtra("wsyNum", wsyNum).putExtra("ysyNum", ysyNum).putExtra("ygqNum", ygqNum));
                }
                break;
            case R.id.fkm:
                ToastUtils.toastShort("暂时没有活动哦！");
                break;

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 10: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startActivityForResult(new Intent(context, LoactionActivity.class),
                            REQUEST_CODE_PICK_CITY);

                } else {
                    android.widget.Toast.makeText(context, "定位需要这个权限", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == -1) {
            if (data != null) {
                String city = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
                BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.CITY, city);
                getLatlon(city);
                tv_leftTitle.setText(city);
//                queryAll("", BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CITY), "", "", "2");
            }
        }
        if (requestCode == 1 && resultCode == -1){
            getMbUserInfo();
            appCouponlist();
            upbranchlist();
        }
    }

    @Override
    public void fetchData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        scrollView.scrollTo(0,0);
        appmbmsgcnt();
        if (!BaseApplication.getInstance().isFirstEnter()){
            tv_leftTitle.setText(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CITY));
        }
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        indexAdvertising();
        slideShow();
        appmbmsgcnt();
        appCouponlist();
        upbranchlist();
        pfl_root.refreshComplete();
    }

    private ArrayList<LinkedTreeMap> imgListLb = new ArrayList<>();
    private ArrayList<LinkedTreeMap> imgListGg = new ArrayList<>();
    private void slideShow() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().slideShow();
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    imgListLb = (ArrayList<LinkedTreeMap>) linkedTreeMap.get("imgList");
                    localImages = new ArrayList<>();
                    if (imgListLb.size()>0){
                        for (int i = 0; i < imgListLb.size();i++){
                            localImages.add(HttpAdapter.HEAD_URL +imgListLb.get(i).get("PATH"));
                        }
                    }
                    //开始自动翻页
                    convenientBanner.setPages(new CBViewHolderCreator() {
                        @Override
                        public Object createHolder() {
                            return new LocalImageHolderView();
                        }
                    },localImages)
                            //设置指示器是否可见
                            .setPointViewVisible(true)
                            //设置自动切换（同时设置了切换时间间隔）
                            .startTurning(2000)
                            //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                            .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                            //设置指示器的方向（左、中、右）
                            .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                            //设置点击监听事件
//                .setOnItemClickListener(this)
                            //设置手动影响（设置了该项无法手动切换）
                            .setManualPageable(true);

                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void indexAdvertising() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().indexAdvertising();
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    imgListGg = (ArrayList<LinkedTreeMap>) linkedTreeMap.get("imgList");
                    if (imgListGg.size()>0){
                        Glide.with(context).load(HttpAdapter.HEAD_URL +imgListGg.get(0).get("PATH")+"").placeholder(R.mipmap.detail_wait).error(R.mipmap.detail_error).into(yhq_gg);
                    }
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void getLatlon(String cityName){

        GeocodeSearch geocodeSearch=new GeocodeSearch(context);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                if (i==1000){
                    if (geocodeResult!=null && geocodeResult.getGeocodeAddressList()!=null &&
                            geocodeResult.getGeocodeAddressList().size()>0){

                        GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                        double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
                        double longititude = geocodeAddress.getLatLonPoint().getLongitude();//经度
                        String adcode= geocodeAddress.getAdcode();//区域编码

                        BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.PROVINCE, geocodeAddress.getProvince());
                    }else {
                        ToastUtils.toastShort("地址名出错");
                    }
                }
            }
        });
        GeocodeQuery geocodeQuery=new GeocodeQuery(cityName.trim(),"29");
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);
    }


}
